package Admin;

import Server.Database.Database;
import Server.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author Paulius Dambrauskas
 */
public class AdminWindowUsers extends JPanel{
    private JButton addUser = new JButton("Pridėti darbuotoją");
    private JButton delUser = new JButton("Trinti darbuotoją");
    private JButton blockUser = new JButton("Blokuoti darbuotoją");
    private JButton projectAdd = new JButton("Pridėti projektą");
    private JButton projectDelete = new JButton("Trinti projektą");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode("Projektai");
    private Database dataBase;
    private JTree users;
    AdminWindowUsers(Database dataBase){
        this.dataBase = dataBase;
        
        //DefaultMutableTreeNode node = new DefaultMutableTreeNode("Test");
        users = new JTree(node);
        JScrollPane userPanel = new JScrollPane(users);
        JPanel buttons = new JPanel(new GridLayout(5, 1));
        buttons.add(addUser);
        buttons.add(delUser);
        
        buttons.add(blockUser);
        buttons.add(projectAdd);
        buttons.add(projectDelete);
        this.setLayout(new BorderLayout());
        this.add("Center", userPanel);
        this.add("East", buttons);
        setOnStart();
        initProjectList();
        initActions();
        expandTree(); 
        
    }
    private void expandTree(){
        for (int i = 0; i < users.getRowCount(); i++) {
            users.expandRow(i);
        } 
    }
    private void setOnStart(){
        delUser.setEnabled(false);
        blockUser.setEnabled(false);
        projectDelete.setEnabled(false);
    }
    private void initProjectList(){
        try {
            //System.out.println("Generuot");
            node.removeAllChildren();
            ArrayList<Project> projects = dataBase.projectRegister.getAllProjects();
            //System.out.println(projects.size());
            for(Project project : projects){
                DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(project.getName());
                for(String user : project.getClients()){
                    projectNode.add(new DefaultMutableTreeNode(user));
                }
                node.add(projectNode);
                
            }
            
        } catch (SQLException ex) {
           System.out.println("MYSQL...beda");
        }
        
    }
    public ArrayList<String> getSelectsArray(ArrayList<JCheckBox> checkBoxes){
        
        ArrayList<String> returnArray = new ArrayList<>();
        for (int i =0; i < checkBoxes.size(); i++){
            if(checkBoxes.get(i).isSelected()){
                //returnArray.add(checkBoxes.get(i).isSelected());
                returnArray.add(checkBoxes.get(i).getText());
            }
        }
        return returnArray;
    }
    private void initActions(){
        users.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                   users.getLastSelectedPathComponent();
              
                //if (node == null) setOnStart();
                if(node.getLevel() == 2){
                    delUser.setEnabled(true);
                    blockUser.setEnabled(true);
                    projectDelete.setEnabled(false);
                     
                }  else if (node.getLevel() == 1){
                    projectDelete.setEnabled(true);
                    delUser.setEnabled(false);
                    blockUser.setEnabled(false);
                } else {
                    setOnStart();
                }

              
            }

           
        });
        delUser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               String selected = users.getLastSelectedPathComponent().toString();
               System.out.println(selected);
               //TODO:
               try{
                    dataBase.usersRegister.deleteUser(selected);
                    initProjectList();
                    users.updateUI();
                    expandTree(); 
               } catch (IllegalArgumentException ex){
                   JOptionPane.showMessageDialog(null, "Administratorių trinti negalima.");
               } catch (SQLException ex) { 
                    Logger.getLogger(AdminWindowUsers.class.getName()).log(Level.SEVERE, null, ex);
                } 
               
            }
        });  
        projectDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               String selected = users.getLastSelectedPathComponent().toString();
               System.out.println(selected);
               //TODO:
               try{
                    dataBase.projectRegister.deleteProject(selected);
                    initProjectList();
                    users.updateUI();
                    expandTree(); 
               }catch(Exception ex){
                   ex.printStackTrace();
               }
            }
        }); 
        addUser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField usernameField = new JTextField();
                JTextField passwordField = new JPasswordField();
                JPanel projectPane = new JPanel();
                ArrayList<JCheckBox> checkBoxes = new ArrayList<>();
                int count = 0;
                try{
                    ArrayList<Project> projects = dataBase.projectRegister.getAllProjects();
                    count = projects.size();
                    //System.out.println(projects.size());

                    for(Project project : projects){
                        checkBoxes.add(new JCheckBox(project.getName()));
                        projectPane.add(checkBoxes.get(checkBoxes.size()-1));

                    }
                } catch(Exception ex){}
                if(count > 0){
                    Object[] message = {
                              "Darbuotojo vardas:", usernameField,
                              "Slaptažodis:", passwordField,
                              "Dalyvauja Projektuose:", projectPane
                    };

                   int option = JOptionPane.showConfirmDialog(null, message, "Darbuotojo prdėjimas", JOptionPane.OK_CANCEL_OPTION);
                   if(option == 0){
                       System.out.println("ADD:" + usernameField.getText() + ":" + passwordField.getText() + ":" + getSelectsArray(checkBoxes));
                        try {
                            dataBase.usersRegister.addUser(usernameField.getText(), passwordField.getText(), getSelectsArray(checkBoxes));
                            initProjectList();
                            users.updateUI();
                            expandTree();
                        } catch (IllegalArgumentException ex) {
                            JOptionPane.showMessageDialog(null,
                                "Palikote tuščią laukelį, arba įrašėte jau egzistuojančio darbuotojo vardą.",
                                "Klaida",
                                JOptionPane.ERROR_MESSAGE);
                        } catch (Exception ex) {
                            Logger.getLogger(AdminWindowUsers.class.getName()).log(Level.SEVERE, null, ex);
                        } 
                   }
                } else {
                    JOptionPane.showMessageDialog(null,
                                "Nėra projektų.",
                                "Klaida",
                                JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        projectAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField nameField = new JTextField();
                JList userList = null;
                //userPane.setSize(200, 200);
                try{
                    ArrayList<String> users = dataBase.usersRegister.getAllUsers();
                    //System.out.println(projects.size());
                    userList = new JList(users.toArray());
                  
                } catch(Exception ex){
                
                }
                JScrollPane userPane  = new JScrollPane(userList);
                Object[] message = {
                          "Projekto pavadinimas:", nameField,
                          "Vykdantys darbuotojai:", userPane
                };
                                               
               int option = JOptionPane.showConfirmDialog(null, message, "Projekto sukūrimas", JOptionPane.OK_CANCEL_OPTION);
               if(option == 0){
                   System.out.println("ADD:"+nameField.getText()+":"+userList.getSelectedValuesList());
                   try{
                        dataBase.projectRegister.addProject(nameField.getText(), userList.getSelectedValuesList());
                        initProjectList();
                        users.updateUI();
                        expandTree(); 
                   } catch (IllegalArgumentException ex) {
                        JOptionPane.showMessageDialog(null,
                                "Palikote tuščią laukelį, arba įrašėte jau egzistuojančio projekto pavadinimą.",
                                "Klaida",
                                JOptionPane.ERROR_MESSAGE);
                   } catch (Exception ex) {
                        Logger.getLogger(AdminWindowUsers.class.getName()).log(Level.SEVERE, null, ex);
                   } 
               }
            }
            
        }); 
        blockUser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selected = users.getLastSelectedPathComponent().toString();
                Boolean admin = true;
                try {
                    admin = dataBase.usersRegister.isAdmin(selected);
                } catch (SQLException ex) {
                    Logger.getLogger(AdminWindowUsers.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (!admin) {
                    JTextField reasonField = new JTextField();
                    
                    if (!dataBase.usersRegister.isUserBlocked(selected)) {
                        Object[] message = {
                                  "Darbuotojo vardas:", selected,
                                  "Priežastis:", reasonField
                        };

                       int option = JOptionPane.showConfirmDialog(null, message, "Darbuotojo blokavimas", JOptionPane.OK_CANCEL_OPTION);
                       if (option == 0) {
                            try {
                                 dataBase.usersRegister.blockUser(selected, reasonField.getText());
                                 AdminWindowBlocks.getInstance().addToList(selected, reasonField.getText());
                            } catch(Exception ex){
                                ex.printStackTrace();
                            }
                            JOptionPane.showConfirmDialog(null, "Darbuotojas sėkmingai įtrauktas į blokuotųjų sąrašą.", "Darbuotojo blokavimas", JOptionPane.OK_CANCEL_OPTION);
                       }
                    }
                    else {
                       JOptionPane.showConfirmDialog(null, "Darbuotojas jau yra užblokuotas.", "Darbuotojo blokavimas", JOptionPane.OK_CANCEL_OPTION);
                    }
                }
                else {
                    JOptionPane.showMessageDialog(null, "Administratorių blokuoti negalima.");
                }
            }
        });
    }
    
    
}
